package com.bioarktech.controller;



import com.bioarktech.entity.Product;
import com.bioarktech.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    /* ------ 前台：首页懒加载 ------ */
    @GetMapping("/api/products/featured")
    @ResponseBody
    public Page<Product> featured(@RequestParam(defaultValue = "0") int page,
                                  @RequestParam(defaultValue = "6") int size) {
        return productService.listHomepage(page, size);
    }

    /* ------ 后台：列表 + 编辑 ------ */
    @GetMapping("/admin/products")
    public String adminList(Model m,
                            @RequestParam(defaultValue = "0") int page,
                            @RequestParam(defaultValue = "10") int size) {
        m.addAttribute("page", productService.list(page, size));
        return "admin/product-list";
    }

    @GetMapping("/admin/products/edit/{id}")
    public String edit(@PathVariable Long id, Model m) {
        m.addAttribute("p", productService.get(id));
        return "admin/product-form";
    }

    @PostMapping("/admin/products/save")
    public String save(Product p) {
        productService.save(p);
        return "redirect:/admin/products";
    }
}
